package com.mock.Controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HttpServletBean;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;



@RestController
@RequestMapping("/api")
public class MockController {

    @PostMapping("/info")
    public ResponseEntity<String> mockPost(@RequestBody String requestBody) {
        // 打印请求体
        System.out.println("Received request body: " + requestBody);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("meg","success");
        return new ResponseEntity<>(jsonObject.toString(), HttpStatus.OK);
    }


    @PostMapping("/allInfo")
    public ResponseEntity<String> allPost(HttpServletRequest request) throws IOException{
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            //获取输入流
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                //字节流转换为字符流
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                //定义数组存放字符
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                //遍历数组获取字符
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
        String requestBody = stringBuilder.toString();
        System.out.println("Received request body: " + requestBody);
        return ResponseEntity.ok("Request body received");
    }
}
